package com.aisupport.deviceidtest;

public class IMEIUtil {
	
	/**
	 * 按位相加
	 * @param num
	 * @return
	 */
	public static int addAll(String num){
		int sum = 0;
		
		for(int i=0;i<num.length();i++){
			sum += Integer.getInteger(num.substring(i, i+1));
		}
		return sum;
	}

	
	public static int check(String imei){
		
		int length=imei.length();
		if(length>14){
			length = 14;
		}
		
		int i=0;
		String resultString = "";
		for(i=0;i<length;i+=2){
			resultString += imei.substring(i, i+1);
			int t = Integer.getInteger( imei.substring(i+1, i+2) )* 2;
			resultString += t+"";
		}
		
		int sum=addAll(resultString)%10;
		
		if(sum!=0){
			sum = 10-sum;
		}
		
		return sum;
	}
	
	public static boolean isValidIMEI(String imei) {
        boolean validation = false;
        if (imei.equals("") == false) {
            validation = (imei.length() == 14) || (((imei.length()>=15) && checkIMEIsum(imei)));
        }
        return validation;
    }

    private static boolean checkIMEIsum(String imei){
        String imei14 = imei.substring(0, 14);
        String checkSum = imei.substring(14,15);
        String validChecksum = getCheckSum(imei14);
        System.out.print("calCheckSum:"+validChecksum + "  checkSum:"+checkSum);
        return checkSum.equals(validChecksum);
    }

    public static String getCheckSum(String imei){
        if (imei.length() == 14) {
            char[] imeiChar=imei.toCharArray();
            int resultInt=0;
            for (int i = 0; i < imeiChar.length; i++) {
                int a=Integer.parseInt(String.valueOf(imeiChar[i]));
                i++;
                final int temp=Integer.parseInt(String.valueOf(imeiChar[i]))*2;
                final int b=temp<10?temp:temp-9;
                resultInt+=a+b;
            }
            resultInt%=10;
            resultInt=resultInt==0?0:10-resultInt;
            return resultInt + "";
        }else{
            return "";
        }
    }


}
